<?php
/*
 * @Author: lokei
 * @Date: 2022-09-24 09:03:54
 * @LastEditors: lokei
 * @LastEditTime: 2023-07-11 17:46:51
 * @Description: 
 */

namespace App\Common\Mp;

use App\Models\Platform\ConfMpModel;
use GuzzleHttp;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Request;

class Common
{
    public static function getAccessToken()
    {
        $appid = '';
        $secret = '';
        if (config('app.proj_identity') != null && config('app.proj_identity') != '') {
            $endapp = Redis::get('proj:' . config('app.proj_identity') . ':mp');
            $endapp_info = json_decode($endapp);
            $appid = $endapp_info->appid;
            $secret = $endapp_info->secret;
        } else {
            $conf = ConfMpModel::first();
            $appid = $conf->appid;
            $secret = $conf->secret;
        }

        if ($appid != '') {
            $redis_key = 'mp_access_token_' . $appid;
            if (Redis::exists($redis_key)) {
                return Redis::get($redis_key);
            } else {
                $http = new GuzzleHttp\Client;
                $params = [
                    'appid' => $appid,
                    'secret' => $secret,
                    'grant_type' => 'client_credential'
                ];
                $response = $http->get('https://api.weixin.qq.com/cgi-bin/token', [
                    'query' => $params
                ]);
                $result = json_decode($response->getBody(), true);
                if(array_key_exists('errcode', $result) && $result['errcode'] != 0) {
                    app('log')->info('获取公众号access token：' . $result['errmsg']);
                    return '';
                } else {
                    Redis::setex($redis_key, intval($result['expires_in']) - 300, $result['access_token']);
                    return $result['access_token'];
                }
            }
        }
        return '';
    }
}
